//
//  TimeUtil.swift
//  aisai
//
//  Created by 陈友文 on 2021/4/13.
//

import Foundation


class TimeUtil: NSObject {
    
    class func getToday()->String{
        return TimeUtil.timeUtilForDate()
    }
    class func getLastDay()->String{
        return TimeUtil.timeUtilForDate(day:-1)
    }
    class func getLastWeek()->String{
        return TimeUtil.timeUtilForDate(day:-7)
    }
    class func getLastMonth()->String{
        return TimeUtil.timeUtilForDate(month:-1)
    }
    class func getHalfLastYear()->String{
        return TimeUtil.timeUtilForDate(month:-6)
    }
    
    
    /// 比较服务器返回的yyyy-MM-dd hh:mm:ss与本地时间差
    /// - Parameter serviceTime: 服务器时间
    class func compareTime(serviceTime:String) -> Bool{
        let current = NSDate().timeIntervalSince1970
        let format = DateFormatter()
        format.dateFormat = "yyyy-MM-dd HH:mm:ss"
        DPrint("compareTime \(serviceTime) \(format.date(from: serviceTime))")
        let service = format.date(from: serviceTime)?.timeIntervalSince1970 ?? 0
        return (service - current >= 0)
    }
    
    /// 求服务器返回的报名开始时间与当前时间差
    /// - Parameter serviceTime: 服务器开始时间
    /// - Returns: 时间差
    class func compareSingupTime(serviceTime:String) ->TimeInterval{
        let current = NSDate().timeIntervalSince1970
        let format = DateFormatter()
        format.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let service = format.date(from: serviceTime)?.timeIntervalSince1970 ?? 0
        
        return service - current
    }
    
    
    
    class func getNowTimeInterval() -> TimeInterval{
        return Date().timeIntervalSince1970
    }
    
    
    class func timeUtilForDate(year:Int = 0 ,month:Int = 0,day:Int = 0) -> String{
        let currtenDate = Date()
        let calendar = Calendar(identifier: .gregorian)
        var dateComps = DateComponents()
        dateComps.year = year
        dateComps.month = month

        dateComps.day = day
        let calculateDate = calendar.date(byAdding: dateComps, to: currtenDate)
        
       
        let format = DateFormatter()
        format.dateFormat = "yyyy-MM-dd"
        return format.string(from: calculateDate!)
    }
    
    
}
